// ==========================================================================
// 云捷GO自动生成业务逻辑层相关代码，只生成一次，按需修改,再次生成不会覆盖.
// 生成日期：2021-07-09 11:02:15
// 生成路径: app/service/module/category/category_service.go
// 生成人：gfcms
// ==========================================================================
package category

import (
	"github.com/gogf/gf/errors/gerror"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/gtime"
	"github.com/gogf/gf/util/gconv"
	"myblog/app/model"
	categoryModel "myblog/app/model/module/category"
	newsModel "myblog/app/model/module/news"
	"myblog/app/utils/convert"
	"myblog/app/utils/excel"
	"myblog/app/utils/page"
	"strings"
)

//根据主键查询数据
func SelectRecordById(id int64) (*categoryModel.EntityExtend, error) {
	return categoryModel.SelectRecordById(id)
}

//根据主键删除数据
func DeleteRecordById(id int64) bool {
	result, err := categoryModel.Delete("id", id)
	if err == nil {
		affected, _ := result.RowsAffected()
		if affected > 0 {
			return true
		}
	}
	return false
}

//批量删除数据记录
func DeleteRecordByIds(ids string) int64 {
	idarr := convert.ToInt64Array(ids, ",")
	//获取子栏目
	idchilds, err := categoryModel.GetChildsById(idarr[0])
	idchilds = append(idchilds, idarr[0])
	//删除所属栏目下的文章
	newsModel.Delete("catid in (?)", idchilds)
	//删除栏目
	result, err := categoryModel.Delete("id in (?)", idchilds)
	if err != nil {
		return 0
	}
	nums, _ := result.RowsAffected()

	return nums
}

//添加数据
func AddSave(req *categoryModel.AddReq, session *ghttp.Session) (int64, error) {
	var entity categoryModel.Entity

	entity.Parentid = req.Parentid
	entity.Catname = req.Catname
	entity.Image = req.Image
	entity.Description = req.Description
	entity.ListTemplate = req.ListTemplate
	entity.ShowTemplate = req.ShowTemplate
	entity.Listorder = req.Listorder
	entity.Ismenu = req.Ismenu
	entity.CreateTime = gtime.Now()

	result, err := entity.Insert()
	if err != nil {
		return 0, err
	}

	id, err := result.LastInsertId()

	if err != nil || id <= 0 {
		return 0, err
	}
	return id, nil
}

//修改数据
func EditSave(req *categoryModel.EditReq, session *ghttp.Session) (int64, error) {
	entity, err := categoryModel.FindOne("id=?", req.Id)
	if err != nil {
		return 0, err
	}

	if entity == nil {
		return 0, gerror.New("数据不存在")
	}
	//删除原有图片
	//if  entity.Image != "" && req.Image != "" {
	//	curDir, _ := os.Getwd()
	//	os.Remove(curDir + "/public/" + entity.Image)
	//}

	entity.Parentid = req.Parentid
	entity.Catname = req.Catname
	entity.Image = req.Image
	entity.Description = req.Description
	entity.ListTemplate = req.ListTemplate
	entity.ShowTemplate = req.ShowTemplate
	entity.Listorder = req.Listorder
	entity.Ismenu = req.Ismenu
	entity.UpdateTime = gtime.Now()

	result, err := entity.Save()

	if err != nil {
		return 0, err
	}

	rs, err := result.RowsAffected()

	if err != nil {
		return 0, err
	}

	return rs, nil
}

//根据条件查询数据
func SelectListAll(params *categoryModel.SelectPageReq) ([]categoryModel.Entity, error) {
	return categoryModel.SelectListAll(params)
}

//根据条件分页查询数据
func SelectListByPage(params *categoryModel.SelectPageReq) ([]categoryModel.Entity, *page.Paging, error) {
	return categoryModel.SelectListByPage(params)
}

// 导出excel
func Export(param *categoryModel.SelectPageReq) (string, error) {
	result, err := categoryModel.SelectListExport(param)
	if err != nil {
		return "", err
	}

	head := []string{"ID", "父级栏目", "栏目名称", "栏目图片", "描述", "排序", "是否导航栏显示", "创建时间", "更新时间"}
	key := []string{"id", "parent_name", "catname", "image", "description", "listorder", "ismenu", "create_time", "update_time"}
	url, err := excel.NewDownlaodExcel(head, key, result)

	if err != nil {
		return "", err
	}

	return url, nil
}

//获取栏目数据
func selectCateTree() ([]categoryModel.EntityExtend, error) {
	return categoryModel.SelectCateTrees()

}

//加载所有菜单列表树
func MenuTreeData() (*[]model.Ztree, error) {
	var result *[]model.Ztree
	menuList, err := selectCateTree()
	if err != nil {
		return nil, err
	}
	result, err = InitZtree(menuList, nil, false)
	if err != nil {
		return nil, err
	}
	return result, nil
}

//对象转菜单树
func InitZtree(menuList []categoryModel.EntityExtend, roleMenuList *[]string, permsFlag bool) (*[]model.Ztree, error) {
	var result []model.Ztree
	isCheck := false
	if roleMenuList != nil && len(*roleMenuList) > 0 {
		isCheck = true
	}

	for _, obj := range menuList {
		var ztree model.Ztree
		ztree.Title = obj.Catname
		ztree.Id = obj.Id
		ztree.Name = transMenuName(obj.Catname, permsFlag)
		ztree.Pid = obj.Parentid
		if isCheck {
			tmp := gconv.String(obj.Id)
			tmpcheck := false
			for j := range *roleMenuList {
				if strings.Compare((*roleMenuList)[j], tmp) == 0 {
					tmpcheck = true
					break
				}
			}
			ztree.Checked = tmpcheck
		}
		result = append(result, ztree)
	}

	return &result, nil
}

func transMenuName(menuName string, permsFlag bool) string {
	if permsFlag {
		return "<font color=\"#888\">&nbsp;&nbsp;&nbsp;" + menuName + "</font>"
	} else {
		return menuName
	}
}

//获取栏目列表
func Catelist(pid int) ([]categoryModel.CateList, error) {
	return categoryModel.Catelist(pid)
}
